package com.bcxj.servicemap.remote;

import com.bcxj.internalcommon.constant.AmapConfigConstants;
import com.bcxj.internalcommon.dto.ResponseResult;
import com.bcxj.internalcommon.response.TerminalResponse;
import com.bcxj.internalcommon.response.TrsearchResponse;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: TerminalClient
 * Package: com.bcxj.servicemap.remote
 * Description:
 *
 * @Author BCXJ
 * @Create 2024/10/31 22:44
 * @Version 1.0
 * @Since 1.0
 */
@Service
@Slf4j
public class TerminalClient {

    @Value("${amap.key}")
    private String key;

    @Value("${amap.sid}")
    private String sid;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 添加终端
     *
     * @param carName
     * @param desc    描述即是车辆的对应的数据的主键id的信息
     * @return
     */
    public ResponseResult addTerminal(String carName, String desc) {

        StringBuilder url = new StringBuilder();
        url.append(AmapConfigConstants.TERMINAL_ADD_URL);
        url.append("?key=").append(this.key);
        url.append("&sid=").append(this.sid);
        url.append("&name=").append(carName);
        url.append("&desc=").append(desc);

        System.out.println(url);
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(url.toString(), null, String.class);
        String body = stringResponseEntity.getBody();

        log.info("添加终端返回结果:{}", body);

        // 解析结果返回tid
        JSONObject jsonObject = JSONObject.fromObject(body);
        JSONObject data = jsonObject.getJSONObject("data");
        String tid = data.getString("tid");

        TerminalResponse terminalResponse = new TerminalResponse();
        terminalResponse.setTid(tid);
        return ResponseResult.success(terminalResponse);
    }


    /**
     * 搜索终端 经度在前，纬度在后
     *
     * @param center
     * @param radius
     * @return
     */
    public ResponseResult<List<TerminalResponse>> arroundSearch(String center, String radius) {
        StringBuilder url = new StringBuilder();
        url.append(AmapConfigConstants.TERMINAL_ARROUNDSEARCH);
        url.append("?key=").append(this.key);
        url.append("&sid=").append(this.sid);
        url.append("&center=").append(center);
        url.append("&radius=").append(radius);


        System.out.println(url);
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(url.toString(), null, String.class);
        String body = stringResponseEntity.getBody();
        System.out.println(body);

        // 解析结果
        JSONObject jsonObject = JSONObject.fromObject(body);
        JSONObject data = jsonObject.getJSONObject("data");
        JSONArray results = data.getJSONArray("results");
        List<TerminalResponse> terminalResponses = new ArrayList<>();
        for (int i = 0; i < results.size(); i++) {
            JSONObject result = results.getJSONObject(i);
            String tid = result.getString("tid");
            Long carId = Long.parseLong(result.getString("desc")); // 为了精度，还是建议先以string读出来，然后通过包装类进行转换

            // 封装经纬度的信息
            JSONObject location = result.getJSONObject("location");
            String latitude = location.getString("latitude");
            String longitude = location.getString("longitude");

            TerminalResponse terminalResponse = new TerminalResponse(tid, carId, latitude, longitude);
            terminalResponses.add(terminalResponse);
        }

        return ResponseResult.success(terminalResponses);
    }


    /**
     * 终端的轨迹的统计
     *
     * @param tid
     * @param startTime
     * @param endTime
     * @return
     */
    public ResponseResult<TrsearchResponse> trsearch(String tid, Long startTime, Long endTime) {
        StringBuilder url = new StringBuilder();
        url.append(AmapConfigConstants.TERMINAL_TRSEARCH);
        url.append("?key=").append(this.key);
        url.append("&sid=").append(this.sid);
        url.append("&tid=").append(tid);
        url.append("&starttime=").append(startTime);
        url.append("&endtime=").append(endTime);


        System.out.println(url.toString());
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url.toString(), String.class);
        System.out.println(forEntity.getBody());

        // 解析结果
        JSONObject jsonObject = JSONObject.fromObject(forEntity.getBody()).getJSONObject("data");

        if (!jsonObject.has("tracks")) {
            return ResponseResult.fail(null);
        }

        JSONArray tracks = jsonObject.getJSONArray("tracks");
        Long distance = 0L;
        Long time = 0L;
        for (int i = 0; i < tracks.size(); i++) {
            JSONObject ele = tracks.getJSONObject(i);
            // 获取数据
            String distanceGet = ele.getString("distance");
            String timeGet = ele.getString("time");
            // 转换数据
            distance += Long.parseLong(distanceGet);
            time += Long.parseLong(timeGet);
        }

        // 数据的封装
        time /= (1000 * 60);
        TrsearchResponse trsearchResponse = new TrsearchResponse();
        trsearchResponse.setDistance(distance);
        trsearchResponse.setTime(time);

        return ResponseResult.success(trsearchResponse);
    }
}
